/**
 * 多语言翻译
 */
import { FC, useEffect, useMemo, useState } from "react";
import { observer, inject } from "mobx-react";
import {
  Row,
  Col,
  Button,
  Modal,
  Form,
  Input,
  message,
  Table,
  Space,
  Popconfirm,
  AutoComplete,
  Tooltip,
} from "antd";
import { EditOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import { ITStore } from "../../store";
import { ITColumns } from "../../store/interfaces";

type TProp = {
  store: ITStore;
};

type TSearchValue = {
  keyward: string | undefined;
};

type Toption = {
  value: string;
  id: string;
};

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

// 搜索和新增按钮组件
const SearchAddComp: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: {
        changeShowAddEditModal,
        lang,
        allLanguage,
        changeSearchLanguage,
      },
    } = store;

    const [form] = Form.useForm();

    const allOptions: Toption[] = useMemo(() => {
      let list: Toption[] = [];
      if (allLanguage && allLanguage.length) {
        allLanguage.forEach((item) => {
          const { cn, en, key, id } = item;
          list.push({
            value: `${key} ${en} ${cn}`,
            id,
          });
        });
      }
      return list;
    }, [allLanguage]);

    // 新增语言按钮
    const handleClickAdd = () => {
      changeShowAddEditModal(true);
    };

    // 重置
    const reset = () => {
      form.resetFields();
      changeSearchLanguage([]);
    };

    // 进行搜索
    const onFinish = (values: TSearchValue) => {
      const { keyward } = values;
      if (keyward) {
        let list: any[] = [];
        allLanguage.forEach((item) => {
          const { en, cn, key } = item;
          if (
            en.toUpperCase().indexOf(keyward.toUpperCase()) !== -1 ||
            cn.toUpperCase().indexOf(keyward.toUpperCase()) !== -1 ||
            key.toUpperCase().indexOf(keyward.toUpperCase()) !== -1
          ) {
            list.push(item);
          }
        });
        changeSearchLanguage(list);
      } else {
        reset();
      }
    };

    // 选择下拉
    const onSelect = (data: string) => {
      allOptions.some((item) => {
        if (item.value === data) {
          const { id } = item;
          allLanguage.some((item) => {
            if (item.id === id) {
              changeSearchLanguage([item]);
              return true;
            }
            return false;
          });
          return true;
        }
        return false;
      });
    };

    return (
      <Row style={{ marginBottom: 20 }}>
        <Col span={20}>
          <Form name="search" layout="inline" form={form} onFinish={onFinish}>
            <Form.Item name="keyward" label={""}>
              <AutoComplete
                style={{
                  width: 320,
                }}
                options={allOptions}
                onSelect={onSelect}
                dropdownMatchSelectWidth={320}
                allowClear={true}
                onClear={reset}
                placeholder={lang["langsearchplaceholder"]}
                filterOption={(inputValue, option): any =>
                  option!.value
                    .toUpperCase()
                    .indexOf(inputValue.toUpperCase()) !== -1
                }
              />
            </Form.Item>
            <Form.Item>
              <Button
                type="primary"
                onClick={() => {
                  form.submit();
                }}
              >
                {lang["langbuttonsearch"]}
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type="default" onClick={reset}>
                {lang["langbuttonreset"]}
              </Button>
            </Form.Item>
          </Form>
        </Col>
        <Col span={4}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            style={{ float: "right" }}
            onClick={handleClickAdd}
          >
            {lang["langbuttonadd"]}
          </Button>
        </Col>
      </Row>
    );
  })
);

interface ITLangDict {
  id?: string;
  key: string;
  en: string;
  cn: string;
  desc: string;
}

// 新增修改语言翻译弹窗
const LangModifyModal: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: {
        lang,
        changeShowAddEditModal,
        showAddEditModal,
        addLanguage,
        editLanguageData,
        changeEditLanguageData,
        updateLanguage,
        getAllLanguage,
      },
    } = store;

    const [form] = Form.useForm();

    useEffect(() => {
      if (editLanguageData) {
        form.setFieldsValue(editLanguageData);
      }
    }, [editLanguageData, form]);

    const close = () => {
      form.resetFields();
      changeEditLanguageData(null);
      changeShowAddEditModal(false);
    };

    const formFinish = async (data: ITLangDict) => {
      let res = null;
      let msg: string = "";
      if (data.id) {
        res = await updateLanguage(data);
        msg = lang["langmodifysuccess"];
      } else {
        res = await addLanguage(data);
        msg = lang["langaddsuccess"];
      }

      if (!res) {
        close();
        getAllLanguage(true);
        message.success(msg);
      } else {
        const { msg } = res;
        message.error(msg);
      }
    };

    return (
      <Modal
        title={
          !!editLanguageData
            ? lang["langlanguageedittitle"]
            : lang["langlanguageaddtitle"]
        }
        open={showAddEditModal}
        destroyOnClose={true}
        onOk={() => {
          form.submit();
        }}
        onCancel={close}
      >
        <Form {...layout} form={form} name="langForm" onFinish={formFinish}>
          <Form.Item name="id" label="" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            name="key"
            label={lang["langkeyword"]}
            rules={[{ required: true }]}
          >
            <Input disabled={!!editLanguageData} />
          </Form.Item>
          <Form.Item
            name="en"
            label={lang["langentext"]}
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="cn"
            label={lang["langcntext"]}
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item name="desc" label={lang["langdescription"]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    );
  })
);

// 语言列表
const LanguageList: FC<TProp | any> = inject("store")(
  observer(({ store }: TProp) => {
    const {
      languageStore: {
        lang,
        allLanguage,
        searchLanguage,
        allLoading,
        changeShowAddEditModal,
        changeEditLanguageData,
        delLoading,
        deleteLanguage,
        getAllLanguage,
      },
    } = store;

    const [delData, setDelData] = useState<ITLangDict | null>(null);

    const [renderData, setRenderData] = useState<any[]>([]);

    useEffect(() => {
      if (searchLanguage.length) {
        setRenderData(searchLanguage);
      } else {
        setRenderData(allLanguage);
      }
    }, [allLanguage, searchLanguage]);

    // 修改语言
    const modifyItem = (data: ITLangDict) => {
      changeEditLanguageData(data);
      changeShowAddEditModal(true);
    };

    // 删除语言
    const deleteItem = async (data: ITLangDict) => {
      setDelData(data);
      const { id } = data;
      const res = await deleteLanguage({ id });
      if (res) {
        getAllLanguage(true);
        message.success(lang["langdeletesuccess"]);
        setDelData(null);
      }
    };

    const columns: ITColumns[] = [
      {
        title: lang["langkeyword"],
        dataIndex: "key",
        key: "key",
      },
      {
        title: lang["langentext"],
        dataIndex: "en",
        key: "en",
      },
      {
        title: lang["langcntext"],
        dataIndex: "cn",
        key: "cn",
      },
      {
        title: lang["langdescription"],
        dataIndex: "desc",
        key: "desc",
      },
      {
        title: lang["langedit"],
        dataIndex: "edit",
        key: "edit",
        width: 110,
        align: "center",
        render: (_: string, record: ITLangDict) => {
          return (
            <Space>
              <Tooltip title={lang["langedit"]}>
                <Button
                  type="link"
                  icon={<EditOutlined />}
                  onClick={() => {
                    modifyItem(record);
                  }}
                />
              </Tooltip>
              <Popconfirm
                title={lang["langconfirmdel"]}
                onConfirm={() => {
                  deleteItem(record);
                }}
              >
                <Tooltip title={lang["langdelete"]}>
                  <Button
                    type="link"
                    danger
                    loading={delData?.id === record.id && delLoading}
                    icon={<DeleteOutlined />}
                  />
                </Tooltip>
              </Popconfirm>
            </Space>
          );
        },
      },
    ];

    return (
      <Table
        dataSource={renderData}
        columns={columns}
        bordered
        loading={allLoading}
      />
    );
  })
);

const Language: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  return (
    <>
      {/* 搜索和新增按钮组件 */}
      <SearchAddComp />

      {/* 列表数据 */}
      <LanguageList />

      {/* 新增修改语言翻译弹窗 */}
      <LangModifyModal />
    </>
  );
};

export default inject("store")(observer(Language));
